import React from 'react';
import ejs from 'ejs';
import path from 'path';
import { Helmet } from 'react-helmet';
import { Provider, useStaticRendering } from 'mobx-react';
import { renderToString } from 'react-dom/server';
import { renderRoutes } from 'react-router-config';
import { StaticRouter } from 'react-router-dom';
import { ChunkExtractor } from '@loadable/server';

useStaticRendering(true);

const statsFile = path.resolve('dist/loadable-stats.json');
const extractor = new ChunkExtractor({ statsFile });

function getStoreState(store) {
    return Object.keys(store).reduce((cur, key) => {
        const item = store[key];
        cur[key] = Object.keys(item).reduce((res, k) => {
            res[k] = item[k];
            return res;
        }, {});
        return cur;
    }, {});
}

export default function render(store, routes, req, context, template) {
    // 取出 store 中的初始数据，放入 window 对象中。
    const initialState = getStoreState(store);
    const jsx = extractor.collectChunks((
        <Provider {...store}>
            <StaticRouter location={req.path} context={context}>
                <div>
                    {renderRoutes(routes)}
                </div>
            </StaticRouter>
        </Provider>
    ));
    const content = renderToString(jsx);

    const helmet = Helmet.renderStatic();
    const scriptTags = extractor.getScriptTags();
    const styleTags = extractor.getStyleTags();

    const html = ejs.render(template, {
        content,
        scriptTags,
        styleTags,
        initialState: JSON.stringify(initialState),
        helmetTitle: helmet.title.toString(),
        helmetMeta: helmet.meta.toString(),
        helmetLink: helmet.link.toString(),
    });

    return html;
}
